﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Xml;
using System.IO;

using Flashado.Framework;

namespace Dropthings.Widget.Widgets.ComWeather
{
	/// <summary>城市类</summary>
	public class City
	{
		private const string __Url = "http://www.weather.com.cn/data/listinfo/city{0}.xml";
		/// <summary>名称</summary>
		public string Name { get; set; }
		/// <summary>ID</summary>
		public string ID { get; set; }
		/// <summary>城市xml路径</summary>
		public static string _CityXmlPath = "WeatherCity.Xml";
		
		private static CityXmlInfo[] _Citys=null;

		public static CityXmlInfo[] Default{
			get{
				if (_Citys == null)
				{
					_Citys = Load(Path.GetFullPath(_CityXmlPath));
				}
				return _Citys;
			}
		}
		public override string ToString()
		{
			return this.Name;
		}
		/// <summary>获取城市类的集合</summary>
		/// <returns>城市类</returns>
		public static City[] GetList()
		{
			return GetList(string.Empty);
		}
		/// <summary>获取城市类的集合</summary>
		/// <param name="id">城市Id</param>
		/// <returns>城市类</returns>
		public static City[] GetList(string id)
		{
			var url = string.Format(__Url, id);
			using (WebClient wc = new WebClient())
			{
				wc.Encoding = Encoding.UTF8;
				string str = wc.DownloadString(url);
				List<City> citys = new List<City>();
				var cs = str.Split(',');
				foreach (var c in cs)
				{
					var carr = c.Split('|');
					citys.Add(new City()
					{
						ID = carr[0],
						Name = carr[1]
					});
				}
				return citys.ToArray();
			}
		}
        /// <summary>
        /// 获取城市代码
        /// </summary>
        /// <param name="name">城市名称</param>
        /// <returns>城市代码</returns>
		public static string GetCityCodeByName(string name){
			var city=Default.FirstOrDefault<CityXmlInfo>(c=>c.Name==name);
			if(city==null){
				return string.Empty;
			}
			return city.Code;
		}
		private static string GetCityByIp(string regex, string input)
		{
			var reg = new Regex(regex);
			var match = reg.Matches(input);
			if(match.Count==0){
				return string.Empty;
			}
			return match[match.Count-1].Result("$1");
		}
        /// <summary>更具IP获取城市代码</summary>
        /// <param name="ipDataPath">IP库地址</param>
        /// <param name="ip">IP地址</param>
        /// <returns>城市代码</returns>
		public static string GetCityCodeByIp(){
            string code = "101190201";
            string respose;
            using (WebClient wc = new WebClient())
            {
                wc.Encoding = Encoding.UTF8;
                respose = wc.DownloadString("http://61.4.185.48:81/g/");
            }
            if (respose.IndexOf("id=") != -1)
            {
                code=respose.Substring(respose.IndexOf("id=")+3, 9);
            }
            return code;
		}
		
		
		public static CityXmlInfo[] Load(string path){
			var cityXmlInfos=new List<CityXmlInfo>();
			var doc=XmlHelper.CreateXmlDocument();
			doc.Load(path);
			var root=doc.DocumentElement;
			foreach(XmlNode node in root.SelectNodes(CityXmlInfo.__City)){
				var cityXmlInfo=new CityXmlInfo();
				cityXmlInfo.Read(node);
				cityXmlInfos.Add(cityXmlInfo);
			}
			return cityXmlInfos.ToArray();
		}
		public static void Save(CityXmlInfo[] cityXmlInfos,string path)
		{
			var doc = XmlHelper.CreateXmlDocument();
			var root = XmlHelper.CreateXmlNode(doc,"root");
			doc.AppendChild(root);
			foreach (CityXmlInfo cityXmlInfo in cityXmlInfos)
			{
				root.AppendChild(cityXmlInfo.ToXmlNode(doc));
			}
			var xtr=new XmlTextWriter(path,Encoding.UTF8);
			xtr.Formatting=Formatting.Indented;
			doc.Save(xtr);
		}
	}
}
